package com.ly.heart.util;

import com.ly.common.core.domain.entity.SysDept;
import com.ly.common.core.domain.entity.SysUser;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.SecurityUtils;
import com.ly.system.service.ISysDeptService;
import com.ly.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

@Component
public class CurrentUserUtil {

    public static CurrentUserUtil currentUserUtil;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ISysDeptService sysDeptService;

    @PostConstruct
    public void init () {
        currentUserUtil = this;
        currentUserUtil.userService = userService;
        currentUserUtil.redisTemplate = redisTemplate;
        currentUserUtil.sysDeptService = sysDeptService;
    }

    /**
     * 获取当前登录用户子公司信息
     * @return
     */
    public static String getCompanyId () {
        String userId = SecurityUtils.getLoginUser ().getUser ().getUserId ();
        if ( Objects.isNull ( userId ) ) {
            //throw new CustomException ( "当前用户ID为空！" );
            return "";
        }
        SysUser sysUser = currentUserUtil.userService.getById ( userId );
        if ( Objects.isNull ( sysUser ) ) {
            //throw new CustomException ( "用户信息不存在！" );
            return "";
        }
        if ( ! Boolean.TRUE.equals ( currentUserUtil.redisTemplate.hasKey ( sysUser.getUserName () ) ) ) {
            //throw new CustomException ( "当前子公司信息为空！" );
            return "";
        }
        return currentUserUtil.redisTemplate.opsForValue ().get ( sysUser.getUserName () ).toString ();
    }

    public static String getDeptId () {
        String userId = SecurityUtils.getLoginUser ().getUser ().getUserId ();
        if ( Objects.isNull ( userId ) ) {
            throw new CustomException ( "当前用户ID为空！" );
        }
        SysUser sysUser = currentUserUtil.userService.getById ( userId );
        if ( Objects.isNull ( sysUser ) ) {
            throw new CustomException ( "用户信息不存在！" );
        }
        return sysUser.getDeptId ();
    }


}
